package com.zhuqiao.tm.netty;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhuqiao.tm.transactional.MyTransaction;
import com.zhuqiao.tm.transactional.MyTransactionManager;
import com.zhuqiao.tm.transactional.TransactionType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NettyClientHandler extends SimpleChannelInboundHandler<String> {

    private ChannelHandlerContext context;
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("接收数据："+ msg);
        JSONObject jsonObject = JSON.parseObject(msg);
        String groupId = jsonObject.getString("groupId");
        String command = jsonObject.getString("command");

        //对事务进行操作
        MyTransaction transaction = MyTransactionManager.getTransactionByGroupId(groupId);
        if("commit".equals(command)){
            transaction.setTransactionType(TransactionType.commit);
        }else {
            transaction.setTransactionType(TransactionType.rollback);
        }

        //通知事务执行
         transaction.getTask().signalTask();


    }


    public synchronized Object call(JSONObject data) throws Exception{
        context.writeAndFlush(data.toJSONString());
        return null;
    }
}
